package pay.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pay.entity.SysUser;
import pay.service.ISysUserJPA;
import pay.utils.FYApiUtil;
import pay.utils.MapSortUtil;
import pay.utils.XmlUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Sheldon Chen on 2017/6/6.
 */
@Component
public class PaymentSchedule {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private ISysUserJPA sysUserService;

    @Value("${fy.mchntCd}")
    private String mchnt_cd;

    @Value("${fy.goldAccount.baseUrl}")
    private String jzhBaseUrl;

    @Value("${fy.goldAccount.pathBaseUrl}")
    private String pathBaseUrl;// 测试环境为/jzh 生产无。

    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

    @Scheduled(cron = "0 00 03 ? * *")
    public void runJob() {
        String sql = "select * from t_payment where subBankName is null and supportCompany like '1%'";
        List<Map<String, Object>> results = this.jdbcTemplate.queryForList(sql);

        logger.info("payment results: " + results.size());

        LocalDate today = LocalDate.now();
        String todayString = today.format(formatter);

        for (int i = 0; i < results.size(); i++) {
            Map<String, Object> result = results.get(i);

            Long userId = (Long)result.get("userId");
            SysUser user = this.sysUserService.findById(userId);

            if (user != null) {
                Map<String, String> map = new HashMap<>();
                map.put("ver", "0.44");
                map.put("mchnt_cd", this.mchnt_cd);
                map.put("mchnt_txn_ssn", "" + System.currentTimeMillis());
                map.put("mchnt_txn_dt", todayString);
                map.put("user_ids", user.getName());
                map = MapSortUtil.sortMapByKey(map);

                String pathUrl = String.format("%s/%s", this.pathBaseUrl, "queryUserInfs.action");
                String response = FYApiUtil.sendPostToFYUtils(map, jzhBaseUrl, pathUrl);

                logger.info("FY response: " + response);
                
                String bankNm = XmlUtils.getVal(response, "bank_nm");

                String paymentUpdateSql = "update t_payment set subBankName = ? where id = ?";
                int count = this.jdbcTemplate.update(paymentUpdateSql, new Object[] {
                        bankNm,
                        result.get("id")
                });
                logger.info("count: " + count);
            }

        }
    }
}
